<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" class="el-breadcrumb">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-button type="primary" @click="addRoleVisible = true"> 添加角色 </el-button>
      <!-- 表格区域 -->
      <el-table :data="rolesList" stripe border class="el-table">
        <!-- 展开列表 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['vcenter', 'bdbottom', id === 0 ? 'bdtop' : '']" v-for="(item, id) in scope.row.children" :key="item.id">
              <!-- 渲染一层权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="['vcenter', id2 === 0 ? '' : 'bdtop']" v-for="(item2, id2) in item.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag closable @close="removeRightById(scope.row, item3.id)" v-for="item3 in item2.children" :key="item3.id" type="warning">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列表 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoles(scope.row.id)">删除</el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%" @close="addRoleDialogClosed">
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="70px">
        <!-- 角色名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="editRoleVisible" width="50%" @close="editRoleDialogClosed">
      <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="70px">
        <!-- 角色名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 展示所有权限对话框 -->
    <el-dialog title="所有权限" :visible.sync="allRighstVisible" width="50%" @close="setRightDialogClosed">
      <el-tree :data="allRightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"> </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allRighstVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      // 添加角色对话框的显示与隐藏
      addRoleVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色表单验证规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, message: '长度必须大于1个字符', trigger: 'blur' },
        ],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }, { trigger: 'blur' }],
      },
      // 修改角色对话框的显示与隐藏
      editRoleVisible: false,
      editRoleForm: {},
      // 修改角色表单验证规则
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, message: '长度必须大于1个字符', trigger: 'blur' },
        ],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }, { trigger: 'blur' }],
      },
      // 展示所有权限列表对话框的显示与隐藏
      allRighstVisible: false,
      // 所有权限数据
      allRightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      // 默认选中的权限数组
      defKeys: [],
      // 当前即将分配权限的角色ID
      roleId: '',
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色信息失败！')
      else {
        this.rolesList = res.data
      }
    },
    // 重置添加角色信息
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 添加角色信息
    async addRoles() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加角色信息失败！')
        else {
          this.$message.success('用户添加成功！')
          // 将添加用户提示框隐藏
          this.addRoleVisible = false
          // 重新加载用户列表
          this.getRolesList()
        }
      })
    },

    // 重置修改角色信息
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 点击修改修改用角色信息
    async showEditDialog(id) {
      console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('查找该角色失败！')
      else {
        console.log(res)
        this.editRoleForm = res.data
        this.editRoleVisible = true
      }
    },
    // 点击确定，修改角色信息
    async editRoles() {
      this.$refs.editRoleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc,
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改角色信息失败！')
        else {
          this.$message.success('用户修改成功！')
          // 将添加用户提示框隐藏
          this.addRoleVisible = false
          // 重新加载用户列表
          this.getRolesList()
        }
      })
    },
    // 删除确认弹框
    async removeRoles(id) {
      const val = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (val !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('查找该角色失败！')
      else {
        this.$message.success('用户删除成功！')
        this.getRolesList()
      }
    },
    // 删除最后一层权限
    async removeRightById(role, rightId) {
      const val = await this.$confirm('此操作将永久删除该角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (val !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
      if (res.meta.status !== 200) return this.$message.error('查找该角色权限失败！')
      else {
        this.$message.success('该角色权限删除成功！')
        // 防止列表刷新，提升用户体验
        role.children = res.data
      }
    },
    // 展示所有权限列表
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('展示所有列表失败！')
      else {
        this.allRightsList = res.data
        this.allRighstVisible = true
        this.getLeafKeys(role, this.defKeys)
      }
    },
    // 通过递归的形式，获取角色权限的Id,并保存到defKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点中不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rights', { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('角色授权失败！')
      } else {
        this.$message.success('角色授权成功！')
        this.getRolesList()
        this.allRighstVisible = false
      }
    },
  },
}
</script>

<style lang="less" scoped>
.el-button {
  margin-bottom: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
